package com.ns.scs.visits.controller;

import com.ns.core.annotations.ReqLog;
import com.ns.core.current.config.SymbolsMark;
import com.ns.core.current.config.SysConst;
import com.ns.core.sentinel.LimitType;
import com.ns.core.sentinel.RateLimiter;
import com.ns.core.utils.StpUtil;
import com.ns.core.utils.cache.RedisUtil;
import com.ns.core.utils.sg.IpUtil;
import com.ns.core.utils.sg.ResultOk;
import com.ns.scs.visits.entry.Visits;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;


/**
 * 用户访问记录
 *
 * @author : liaowei
 * @since : 2025-01-07 10:42:33
 */
@Slf4j
@RestController
@RequestMapping("/visits")
@RequiredArgsConstructor
@CrossOrigin
public class VisitsController {

    @GetMapping("add")
    @ReqLog(module = "访问量模块", name = "访问量", authFlag = false)
    @RateLimiter(time = 5, count = 15, limitType = LimitType.IP)
    public ResultOk save() {
        HttpServletRequest request = IpUtil.getRequest();
        String ip = IpUtil.getIP(request);
        Set<Object> cacheIps = RedisUtil.forSetGet(SysConst.SCS_VISITS + SymbolsMark.COLON + SymbolsMark.IP);
        // 访问ip
        boolean flag = cacheIps.stream()
                .anyMatch(cacheIp -> StringUtils.pathEquals(String.valueOf(cacheIp), ip));
        if (!flag) {
            RedisUtil.forSetAdd(SysConst.SCS_VISITS + SymbolsMark.COLON + SymbolsMark.IP, ip);
            // 访问对象
            Visits visits = new Visits();
            visits.setIp(ip);
            visits.setSid(StpUtil.getSid());
            visits.setUid(StpUtil.getLoginUserId());
            String header = request.getHeader(SymbolsMark.HEADER_USER_AGENT);
            visits.setUserAgent(header);
            // 客户端所在地址
            visits.setArea(IpUtil.getRequest().getRemoteAddr());
            // 记录访问
            RedisUtil.forListAdd(SysConst.SCS_VISITS, visits);
        }
        return ResultOk.getSuccess();
    }
}
